//
//  DeviceTCPManager.m
//  LazyHome
//
//  Created by yh on 2018/3/30.
//  Copyright © 2018年 yh. All rights reserved.
//

#import "DeviceTCPManager.h"
#import "NSMutableData+BufferHandler.h"
@implementation DeviceTCPManager

+ (instancetype)shareManager{
    static dispatch_once_t onceToken;
    static DeviceTCPManager *shareInstance = nil;
    dispatch_once(&onceToken, ^{
        shareInstance = [[DeviceTCPManager alloc]init];
    });
    return shareInstance;
}

- (TCPClient *)creatClientWithHost:(NSString *)host port:(NSString *)port localport:(NSString *)localport error:(NSError *__autoreleasing *)errPtr{
   TCPClient *client = [TCPClient clientWithHost:host port:port localport:localport error:errPtr];
    client.delegate = self;
    [self.clients addObject:client];
    return client;
}

- (void)sendMessage:(LHMessage *)msg toClient:(TCPClient *)clinet success:(void(^)(LHMessage *message))success failure:(void(^)(void))failure{
    [clinet sendData:[msg messageData] withTimeout:-1 tag:-1];
}


- (BOOL)tcpClient:(TCPClient *)tcpClient shouldReconnectForNetChange:(AFNetworkReachabilityStatus)networkReachabilityStatus{
    return YES;
}

- (void)tcpClient:(TCPClient *)tcpClient socket:(GCDAsyncSocket *)sock didWriteData:(NSData *)data withTag:(long)tag{
    
    
}

- (void)tcpClient:(TCPClient *)tcpClient socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{

    LHMessage *msg = [[LHMessage alloc]init];
    while (tcpClient.reciveBuffer.handle_index.integerValue < tcpClient.reciveBuffer.length) {
        NSData *dat = [tcpClient.reciveBuffer readDataWithLength:1];
        if ([dat toUChar] == 0xaa) {
            msg.headData = dat;
            break;
        }
    }
    if (tcpClient.reciveBuffer.handle_index.integerValue + 1 < tcpClient.reciveBuffer.length) {
        msg.fnData = [tcpClient.reciveBuffer readDataWithLength:1];
    }else{
        [tcpClient.reciveBuffer resetHandleIndex2Zero];;
    }
    
    if (tcpClient.reciveBuffer.handle_index.integerValue + 2 < tcpClient.reciveBuffer.length) {
        msg.cmdData = [tcpClient.reciveBuffer readDataWithLength:2];
    }else{
        [tcpClient.reciveBuffer resetHandleIndex2Zero];;
    }
    
    if (tcpClient.reciveBuffer.handle_index.integerValue + 2 < tcpClient.reciveBuffer.length) {
        msg.lengthData = [tcpClient.reciveBuffer readDataWithLength:2];
    }else{
        [tcpClient.reciveBuffer resetHandleIndex2Zero];;
    }
   
    if (tcpClient.reciveBuffer.handle_index.integerValue + [msg.lengthData toUShort] <= tcpClient.reciveBuffer.length) {
        msg.data = [tcpClient.reciveBuffer readDataWithLength: [msg.lengthData toUShort]];
        //解析完一帧了
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_TCP_MESSAGE_CAME object:msg];
    }else{
        [tcpClient.reciveBuffer resetHandleIndex2Zero];;
    }
    
}

@end
